#! usr/bin/python

# -*- coding: utf-8 -*-

import re
import subprocess
import sys
import threading
import os
import math
from rpy2.robjects import r
import rpy2.robjects as ro
from core import processing as proc
from PyQt4 import QtCore, QtGui

import Creation_XML
from core import objects as obj



class integration_by_xcms(QtCore.QObject) :
	"""Allows integration of peak calling xcms"""
	
	def __init__(self, lspl):
		"""Constructor, need to emit signals:
		@Rcommand
		@Rfile
		"""
		
		QtCore.QObject.__init__(self)
		
		self.lspl = lspl
		self.peaklist =[] #list of list for printing in GUI
		self.transformed_xml = []

		self.RCOMMAND = "Rscript"
		self.RFILE = "xcms_integration.R"
		self.cmd_line = (lambda a,b: "".join([" ".join([a, b])," "])) (self.RCOMMAND, self.RFILE)

	#TODO modify to use only specified file in GUI lspl list de file name
	def transformation(self):
		"""Transformation into a new xml"""
		
		for spl in self.lspl:
			xml_creator = Creation_XML.createXMLFile( spl.getXmlFile(), spl.getSpectra(), spl.getHeader() )
			xml_creator.writing_xml()
			self.transformed_xml.append(xml_creator.get_new_file())
				
	
	def makeReport (self, time_width=6):
		"""Just for printing the result """
		
		self.line =""
		for i in xrange (len(self.peaklist)):
			saving ={}
			for j in xrange (i+1,len(self.peaklist)):
				for k,peaka in enumerate(self.peaklist[i]):
					saving[(peaka.rt, peaka.transition)] = str(peaka.transition[0])+','+str(peaka.rt)+','+str(int(math.floor(float(peaka.area))))
					for peakb in self.peaklist[j]:
						if abs( float(peaka.rt) - float(peakb.rt)) < time_width and peaka.transition == peakb.transition:
							saving[(peaka.rt, peaka.transition)]+= ','+str(peakb.rt)+','+str(int(math.floor(float(peakb.area))))
			for val  in sorted(saving.iterkeys()):# just remove iterkeys by keys
				self.line += saving[val]+'\n'
		with open( "peak", 'w') as f:
			f.write("transition, retentiontime, intensity(*number of files)\n")
			f.write (self.line)
		return self.line
		
	def erasing_trace (self): 
		"""erase new transition file"""
		pass #eliminate transition file mzxml.txt
	
	def testing (self):
		line=""
		for xml in self.transformed_xml:
			line += xml+" "
		return line
	
	
	def buildModels(self):pass
	"""
	TO DO
	"""
	
	def make_new_sample(self, spl, files_to_merge):
		lspl = obj.ListSample()
		for filename in files_to_merge:
			lspl.append(self.lspl.Sample(filename))
		chrom = proc.Merging_Chromatograms(lspl)
		spectra = proc.Merging_Spectra(lspl)
		peaks = proc.Merging_Peaks(lspl)
		spl.setChromatogram(chrom)
		spl.setSpectra(spectra)
		spl.set_peak_list(peaks)
		return spl
		
	#lspl file name to integrate and align
	
	def integrate_align (self, fwhm=0, step=0, steps=0, mzdiff=0, snthresh=0, max=0, plot =True, retcor=None):
		"""
		Calling XCMS now
		"""
		"""
		self.cmd_line += str(len(self.transformed_xml))+' '+self.testing()+str(fwhm) +' '+ str(step)\
						+' '+str(steps)+' '+str(mzdiff)+' '+ str(snthresh)+' '+ str(max) +' '+retcor
					
		p = subprocess.Popen(str(self.cmd_line).split('\s'),shell =True)
		p.wait()
		
		"""
		r.library("xcms")
		write_table = r["write.table"]

		if plot: sleep =0.001
		else: sleep= 0
		test = r.xcmsSet(ro.StrVector(self.transformed_xml), fwhm = fwhm,  step = step, steps =steps, mzdiff =mzdiff, snthresh =snthresh, max= max, sleep =sleep)
		test_2 = r.group(test)
		test_3 =r.retcor(test_2, method =retcor)
		r.plotrt(test_3)
		test_4 =r.group(test_3)
		#test_5 = r.fillPeaks(test_4)
		write_table(r.peaks(test_4), r.paste("peaks"), sep=';')
